import apiClient from './api';
import { TaskLogResponse, TaskLogRequest, ApiResponse } from '@/types/api';

/**
 * 日志相关API服务
 */
export class LogsAPI {
  /**
   * 获取训练任务日志
   * @param taskId 任务ID
   * @param params 查询参数
   * @returns 任务日志响应
   */
  static async getTrainingTaskLogs(
    taskId: string, 
    params?: TaskLogRequest
  ): Promise<ApiResponse<TaskLogResponse>> {
    try {
      const response = await apiClient.get(`/training-tasks/${taskId}/logs`, {
        params: {
          start_line: params?.start_line || 1,
          end_line: params?.end_line,
          max_lines: params?.max_lines || 1000,
          level_filter: params?.level_filter
        }
      });
      return response;
    } catch (error) {
      console.error('获取任务日志失败:', error);
      throw error;
    }
  }

  /**
   * 获取训练任务日志（分页）
   * @param taskId 任务ID
   * @param page 页数
   * @param pageSize 每页大小
   * @param levelFilter 日志级别过滤
   * @returns 任务日志响应
   */
  static async getTrainingTaskLogsPaginated(
    taskId: string,
    page: number = 1,
    pageSize: number = 100,
    levelFilter?: string
  ): Promise<ApiResponse<TaskLogResponse>> {
    const startLine = (page - 1) * pageSize + 1;
    const endLine = page * pageSize;
    
    return this.getTrainingTaskLogs(taskId, {
      start_line: startLine,
      end_line: endLine,
      max_lines: pageSize,
      level_filter: levelFilter
    });
  }

  /**
   * 获取最新的训练任务日志
   * @param taskId 任务ID
   * @param maxLines 最大行数
   * @param levelFilter 日志级别过滤
   * @returns 任务日志响应
   */
  static async getLatestTrainingTaskLogs(
    taskId: string,
    maxLines: number = 100,
    levelFilter?: string
  ): Promise<ApiResponse<TaskLogResponse>> {
    return this.getTrainingTaskLogs(taskId, {
      max_lines: maxLines,
      level_filter: levelFilter
    });
  }

  /**
   * 获取特定级别的训练任务日志
   * @param taskId 任务ID
   * @param level 日志级别 (INFO, DEBUG, WARNING, ERROR)
   * @param maxLines 最大行数
   * @returns 任务日志响应
   */
  static async getTrainingTaskLogsByLevel(
    taskId: string,
    level: 'INFO' | 'DEBUG' | 'WARNING' | 'ERROR',
    maxLines: number = 1000
  ): Promise<ApiResponse<TaskLogResponse>> {
    return this.getTrainingTaskLogs(taskId, {
      level_filter: level,
      max_lines: maxLines
    });
  }

  /**
   * 实时获取训练任务日志（轮询）
   * @param taskId 任务ID
   * @param callback 日志更新回调函数
   * @param interval 轮询间隔（毫秒）
   * @returns 停止轮询的函数
   */
  static startLogPolling(
    taskId: string,
    callback: (logs: TaskLogResponse) => void,
    interval: number = 3000
  ): () => void {
    let intervalId: NodeJS.Timeout;
    let lastLineCount = 0;

    const poll = async () => {
      try {
        const response = await this.getLatestTrainingTaskLogs(taskId);
        if (response.success && response.data) {
          // 只有当日志行数发生变化时才触发回调
          if (response.data.total_lines !== lastLineCount) {
            lastLineCount = response.data.total_lines;
            callback(response.data);
          }
        }
      } catch (error) {
        console.error('轮询日志失败:', error);
      }
    };

    // 立即执行一次
    poll();
    
    // 设置定时轮询
    intervalId = setInterval(poll, interval);

    // 返回停止函数
    return () => {
      if (intervalId) {
        clearInterval(intervalId);
      }
    };
  }
}

export default LogsAPI; 